package jrobutt.room;

import jrobutt.*;

import java.awt.*;
import java.awt.geom.AffineTransform;

public class FpsCounter implements Updatable, Renderable
{
    private static final Font font = new Font("verdana", Font.PLAIN, 16);
    
    private long last_time_nanos;
    private int fps;
    private String fps_message;
    
    public FpsCounter ()
    {
        last_time_nanos = System.nanoTime();
        fps = 0;
        fps_message = "? fps";
    }
    
    public void update ()
    {
        long current_time_nanos = System.nanoTime();
        if (current_time_nanos - last_time_nanos > 1000000000)
        {
            fps_message = fps + " fps";
            fps = 0;
            last_time_nanos = current_time_nanos;
        }
        fps++;
    }
    
    public void render (Graphics2D g)
    {
        AffineTransform prev_transform = g.getTransform();
        g.setTransform(Global.identity_transform);
        {
            g.setFont(font);
            
            FontMetrics fm = g.getFontMetrics();
            int width = fm.stringWidth("100 fps");
            int height = fm.getHeight();
            int x = 4;
            int y = 16;
            int n = 4;
            
            g.setColor(Color.BLACK);
            g.fillRect(x - n, y - height - n, width + n*2, height + n*2);
            
            g.setColor(Color.WHITE);
            g.drawString(fps_message, x, y);
        }
        g.setTransform(prev_transform);
    }
}
